package cn.wwcyc.controller;

import cn.wwcyc.domain.*;
import cn.wwcyc.exception.WWExceptionEnum;
import cn.wwcyc.mapper.UserMapper;
import cn.wwcyc.service.UserService;
import cn.wwcyc.utils.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")

public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    UserMapper userMapper;


    @PostMapping("/login")
    public R<UserVo> longin(@RequestBody User user) {

        User u;
        UserVo uv = new UserVo();
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", user.getUsername());
        qw.eq("password", user.getPassword());
        try {
            u = userService.getOne(qw);
            if (u != null) {
                BeanUtils.copyProperties(u, uv);
                String token = JWTUtil.getToken(uv, 1000 * 60 * 60 * 12);//有效期12h
                uv.setToken(token);
                List<UserRoleMenuVo> userList = userMapper.getUserRoleMenuVo(user.getUsername());
                for (UserRoleMenuVo userRoleMenuVo : userList) {
                    if (userRoleMenuVo.getId() == uv.getId()) {
                        uv.setMenuList(userRoleMenuVo.getMenuList());
                    }
                }
                List<Menu> menuTreeList = MenuListtoTree(uv.getMenuList());
                uv.setMenuTree(menuTreeList);
                return R.success(uv);
            } else {
                return R.error(WWExceptionEnum.ERROR_USERNAME_PASSWORD);
            }
        } catch (Exception e) {
//            WWExceptionEnum wwe = new WWExceptionEnum;
            System.out.println(e.getMessage());
            return R.error(WWExceptionEnum.SYSTEM_ERROR);
//            return null;
        }
    }

    @GetMapping("/changePassword")
    public R changePassword(@RequestParam Long userId, @RequestParam String oldpassword, @RequestParam String newpassword) {
        System.out.println(userId);
        System.out.println(oldpassword);
        userService.changePassword(userId, oldpassword, newpassword);
        return R.success();

    }

    private List<Menu> MenuListtoTree(List<Menu> menuList) {
        List<Menu> menuTreeList = null;
        if (menuList != null && menuList.size() > 0) {
            menuTreeList = new ArrayList<>();
            for (Menu menu : menuList) {
                if (menu.getPid() == null) {
                    List<Menu> children = getMenuChildren(menu, menuList);
                    menu.setChildren(children);
                    menuTreeList.add(menu);
                }
            }
            menuTreeList.sort((o1, o2) -> {
                if (o1.getXh() == null)
                    return 1;
                return o1.getXh().compareTo(o2.getXh());
            });
            return menuTreeList;
        }
        return null;
    }

    private List<Menu> getMenuChildren(Menu menu, List<Menu> menuList) {
        List<Menu> children = null;
        if (menuList != null && menuList.size() > 0) {
            children = new ArrayList<>();
            for (Menu m : menuList) {
                if (m.getPid() == menu.getId()) {
                    children.add(m);
                }
            }
            for (Menu m : children) {
                List<Menu> grandson = getMenuChildren(m, menuList);
                m.setChildren(grandson);
            }
        }
        if (children != null) {
            children.sort((o1, o2) ->
            {
                if (o1.getXh() == null)
                    return 1;
                return o1.getXh().compareTo(o2.getXh());
            });
        }
        return children;
    }

    @GetMapping("/getpage")
    public R<IPage<User>> getpage(@RequestParam Integer pagenum, @RequestParam Integer pagesize) {
        IPage<User> page = new Page<>(pagenum, pagesize);
        page = userService.page(page);
        return R.success(page);
    }

    @PostMapping("/save")
    public R save(@RequestBody User user) {
        userService.save(user);
        return R.success();
    }

    @PostMapping("/savewithroles")
    public R savewithroles(@RequestBody UserVo user) {
//        System.out.println(user);
        userService.saveWithRoles(user);
        return R.success();
    }

    @PostMapping("/editwithroles")
    public R editwithroles(@RequestBody UserVo user) {
//        System.out.println(user);
        userService.editWithRoles(user);
        return R.success();
    }

    @PostMapping("/edit")
    public R edit(@RequestBody User user) {
//        System.out.println(user);
        //原始的update不能处理roleid为空的情况！，这里自己写一个
        Integer i = userService.myUpdateById(user);
        return R.success(i);
    }

    @DeleteMapping
    public R del(Integer id) {
//        userService.save(user);
        userService.removeById(id);
        return R.success();
    }

    @GetMapping("/getpage1")
    public R<IPage<UserRoleMenuVo>> getpage1(@RequestParam Integer pagenum, @RequestParam Integer
            pagesize, @RequestParam(required = false) String username) {

        IPage<UserRoleMenuVo> page = new Page<>(pagenum, pagesize);
        page = userService.getUserRoleMenuVo(page, username);
        return R.success(page);
    }
}
